import _ from "lodash";
import $ from "jquery";
import commonStore from "../../store/admin/common"
import {message, Modal} from 'antd'
import swal from "sweetalert2";
import {action} from 'mobx'
import {IS_OK} from '$config/admin/state_code'
let EventBus = $("body");

export let getMenuConfigByHash = (Hash,navData) =>{
    return  _.chain(navData)
        .map(item => {
            if(item.child.length > 0){
                _.each(item.child,( child )=>{
                    child.parent = _.cloneDeep(item);
                    delete child.parent.child;
                });
                return item.child
            }
            return item;
        })
        .map(item =>{
            let Items = item;
            if(Array.isArray(Items)) {
                _.each(Items,itemChild =>{
                   if(itemChild.child.length > 0) {
                       _.each(itemChild.child,( child )=>{
                           child.parent = _.cloneDeep(itemChild);
                           delete child.parent.child;
                       });
                       Items = [...Items,...itemChild.child];
                   }
                })
            }
            return Items
        })
        .flatten()
        .filter(item => {
          let reg = item.reg ? new RegExp(item.reg) : item.href;
          return item.reg ? reg.test(Hash) : item.href === Hash
        })
        .value();
};

export let getMenuConfigNodeByText = (TextArr,navData) =>{
    let ObjArr = [];
    let FindObjByText = function(data){
        if(TextArr.indexOf(data.text)!== -1 ){
            ObjArr.push(data);
        }
    };
    let HasChild = function(data){
        _.each(data,(child)=>{
           if(child.child.length > 0){
               FindObjByText(child);
               HasChild(child.child)
           }else{
               FindObjByText(child);
           }
        });
    };
    HasChild(navData);
    return ObjArr
};

export let eventBus = EventBus;

export let ControlWithEvent = function (url) {
   if(location.hash.replace("#",'') !== url ) {
       location.replace(`#${url}`);
       EventBus.trigger("router-change");
       commonStore.LoadingBarState = true;
   }
};

export let Log = function (obj) {
    console.log.call(console,obj)
};

export let askModel = function (opt) {
    const ref = Modal.confirm({
      title: opt.title || "询问",
      content: opt.content || "是否删除?",
      okText: opt.okText || "删除",
      cancelText: opt.cancelText || "取消",
      onOk:function () {
        opt.onOk();
        ref.destroy();
      },
      onCancel: opt.onCancel || function () {}
    });
    return ref
};

export let eventPreventByClassNames = function (e,classNames) {
    let target = e.target;
    let needPrevent = false;
    _.each(classNames,(name)=>{
        if(target.className.indexOf(name) !== -1){
            needPrevent = true;
        }
    });
    return needPrevent;
};

export let cloneObj = function (obj) {
    return JSON.parse(JSON.stringify(obj))
};

export let appendKeyToArr = function (arr,prefix) {
    return _.map(arr,(item)=>{
        item.key = prefix ? `${prefix}${_.uniqueId()}`: _.uniqueId();
        return item;
    });
};

export let swalFn = {
    inquire: function (Options, scuccesFn, canceFn) {
        return swal({
            title: Options.title || '确认删除?',
            text: Options.text || "",
            type: Options.type || 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            cancelButtonText: "取消",
            confirmButtonText: '确定'
        }).then(function (result) {
            if (result.value) {
                typeof scuccesFn === "function" ? scuccesFn(result) : null;
            } else {
                typeof canceFn === "function" ? canceFn(result) : null
            }
        })
    },
    swal
};

export let scollTop = function () {
  $(".ant-layout").scrollTop(0)
};

//定义 object 属性
export let def = function (obj, key, props) {
  Object.defineProperty(obj, key, props);
};
//简单的message
export let easyMessage = function (error_code,msg,successFn = function(){},errorFn= function(){}) {
    message[error_code === IS_OK ? 'success' : 'error'](msg);
    error_code === IS_OK ? successFn() : errorFn();
};

export function resetDefault(val) {
  return function (target, name, descriptor) {
    if (target.DEFAULT_STATE) {
      target.DEFAULT_STATE[name] = val;
    } else {
      target.DEFAULT_STATE = {};
      target.DEFAULT_STATE[name] = val;
    }
    return descriptor
  }
}

export let canReset = action(function (target) {
  target.prototype.ResetDefault = function () {
    let self = this;
    _.each(target.prototype.DEFAULT_STATE, (val, key) => {
      if (_.isFunction(val)) {
        self[key] = new val();
      } else {
        self[key] = _.cloneDeep(val);
      }
    })
  }
});


